<?php
/**
 * Created by PhpStorm.
 * User: zhangyurong
 * Date: 2017/3/25
 * Time: 15:20
 */

namespace App\Repositories\Eloquent;

use App\Facades\Site as OpenSite;

class YiwangAccessToken
{
    public $dbhost="";//主机
    public $dbname = '';//数据库
    public $dbuser = 'root';//用户名
    public $dbpass = '';//密码
    public $table='cms_access_token';//AccessToken表名
    public $pdo;//pdo链接

    public $token = '1';//平台上的token值
    public $unionid = '50';//你的平台的id
    public $effective_second = '604800';//有效时间
    public $url = 'https://www.1wyun.com';//平台地址


    /**
     * 初使化数据库链接
     * YiwangAccessToken constructor.
     */
    public function  __construct()
    {
        //动态调用原网站的数据库配置,如使用动态调用请去除注释并修改
        $this->dbhost=env('DB_HOST');
        $this->dbname=env('DB_DATABASE');
        $this->dbuser=env('DB_USERNAME');
        $this->dbpass=env('DB_PASSWORD');

        $this->unionid=OpenSite::get('yiwang_unionid');
        $this->token=OpenSite::get('yiwang_token');

        try {
            $pdo =new \PDO("mysql:host=".$this->dbhost.";dbname=".$this->dbname,$this->dbuser,$this->dbpass);
            $pdo->setAttribute($pdo::ATTR_PERSISTENT, true);  // 设置数据库连接为持久连接
            $pdo->setAttribute($pdo::ATTR_ERRMODE, $pdo::ERRMODE_EXCEPTION);  // 设置抛出错误
            $pdo->setAttribute($pdo::ATTR_ORACLE_NULLS, true);  // 设置当字符串为空转换为 SQL 的 NULL
            $pdo->query('SET NAMES utf8');  // 设置数据库编码
            // return $pdo;
            $this->pdo = $pdo;
        } catch (PDOException $e) {
            exit('数据库连接错误，错误信息：'. $e->getMessage());
        }
    }

    /**
     * access_token验证
     * @param $access_token
     */
    public function checkAccessToken($access_token) {
        $sql="select * from `".$this->table."` where name='1wyun_open' limit 1";
        $res=$this->pdo->query($sql);
        $result = $res->fetch();

        if(empty($result['id'])){//第一次使用直接放行
            $this->getAccessToken();
        }elseif($result['access_token'] != $access_token){
            //2.2在数据库有access_token的基础上，必须验证传过来的access_token
            echo json_encode(array('status'=>0,'msg'=>$access_token.'--access_token验证失败'));
            die;
        }
    }

    /**
     * 获取access_token
     * @param $access_token_find
     * @return mixed
     */
    public function getAccessToken(){
        $sql="select * from `".$this->table."` where name='1wyun_open' limit 1";
        $res=$this->pdo->query($sql);
        $result = $res->fetch();
        if(empty($result['id'])){//数据库中不存在时创建
            $data=$this->remoteGetAccessToken();
            if($data->status == '200'){
                $access_token = $data->access_token;
                $effective_time = $data->effective_time;
                $intoSql = "insert into `".$this->table."` (name,access_token,effective_time) values";
                $intoSql .= "('1wyun_open','".$access_token."','".$effective_time."')";
                $this->pdo->query($intoSql);
                return $access_token;
            }else{
                die("获取access_token失败!");
            }
        }elseif($result['effective_time']<(time()+100)){//过期重新创建
            $data=$this->remoteGetAccessToken();
            if($data->status == '200'){
                $access_token = $data->access_token;
                $effective_time = $data->effective_time;
                $sql ="update `".$this->table."` set access_token = '".$access_token."', effective_time = '".$effective_time."' where name = '1wyun_open'";
                $this->pdo->query($sql);
                return $access_token;
            }else{
                die("获取access_token失败!");
            }
        }else{
            return $result['access_token'];
        }
    }


    /**
     * 远程获取access_token
     * @return mixed
     */
    protected function remoteGetAccessToken(){
        $url = $this->url."/get_access_token";
        $post_data=array();
        $post_data['unionid'] = $this->unionid;//在平台注册的id
        $post_data['token'] = $this->token;//在平台留的token
        $post_data['effective_second'] = $this->effective_second;//定义返回的access_token有效期
        $curl_data = $this->curlPost($url,$post_data);
        $data = json_decode($curl_data);
        if(empty($data->status)){
            die('无法链接一网云服务端!');
        }else{
            return $data;
        }
    }

    //curl提交
    public function curlPost($url,$post_data){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        $curl_data = curl_exec($curl);
        curl_close($curl);
        return $curl_data;
    }

}